<template>
	<el-dialog v-model="visible" :title="opType == 1 ? '设置职务' : opType == 2 ? '设置权限' : opType == 3 ? '重置用户密码' : opType == 4 ? '查看职务权限' : !dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :width="opType == 2 ? 900 : 600" :destroy-on-close="true">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px" @keyup.enter="submitHandle()">
			<el-form-item prop="strator_account" label="账号">
				<el-input v-model="dataForm.strator_account" placeholder="账号名" :disabled="!!opType" maxlength="20"></el-input>
			</el-form-item>
			<!-- <el-form-item prop="realName" label="姓名">
				<el-input v-model="dataForm.realName" placeholder="姓名"></el-input>
			</el-form-item> -->
			<!-- <el-form-item prop="orgId" label="所属部门">
				<el-tree-select
					v-model="dataForm.orgId"
					:data="orgList"
					value-key="id"
					:props="{ label: 'name', children: 'children' }"
					style="width: 100%"
				/>
			</el-form-item> -->
			<el-form-item prop="strator_mobile" label="手机号">
				<el-input v-model="dataForm.strator_mobile" placeholder="手机号" :disabled="!!opType" maxlength="11"></el-input>
			</el-form-item>
			<el-form-item prop="strator_email" label="邮箱">
				<el-input v-model="dataForm.strator_email" placeholder="邮箱" :disabled="!!opType" maxlength="50"></el-input>
			</el-form-item>
			<el-form-item prop="strator_nickname" label="昵称">
				<el-input v-model="dataForm.strator_nickname" placeholder="昵称" :disabled="!!opType" maxlength="20"></el-input>
			</el-form-item>
			<el-form-item prop="strator_password" label="密码" v-if="!dataForm.id || opType == 3">
				<el-input v-model="dataForm.strator_password" type="strator_password" placeholder="密码" maxlength="20"></el-input>
			</el-form-item>
			<el-form-item prop="parentName" label="所属部门" class="org-list">
				<el-popover ref="orgListPopover" placement="bottom-start" trigger="click" :width="400" popper-class="popover-pop" :disabled="isRole">
					<template #reference>
						<el-input v-model="dataForm.parentName" :readonly="true" placeholder="上级部门" :disabled="isRole">
							<template #suffix>
								<svg-icon v-if="dataForm.pid !== '0' && !isRole" icon="icon-close-circle" @click.stop="treeSetDefaultHandle()"></svg-icon>
							</template>
						</el-input>
					</template>
					<div class="popover-pop-body">
						<el-tree
							ref="orgListTree"
							:data="orgList"
							:props="{ label: 'department_name', children: 'children' }"
							node-key="id"
							:default-expand-all="true"
							:highlight-current="true"
							:expand-on-click-node="false"
							accordion
							@current-change="treeCurrentChange"
						>
						</el-tree>
					</div>
				</el-popover>
			</el-form-item>
			<el-form-item prop="position_ids" label="所属职务" v-if="opType == 1 || opType == 4">
				<el-select v-model="dataForm.position_ids" multiple placeholder="所属职务" style="width: 100%" :disabled="opType == 4">
					<el-option v-for="role in roleList" :key="role.id" :label="role.position_name" :value="role.id"></el-option>
				</el-select>
			</el-form-item>
			<el-row v-if="opType == 2">
				<el-col :span="24">
					<el-form-item label="菜单权限">
                        <div class="w100">
                            <el-scrollbar max-height="400px" always :min-size="30">
                                <el-tree ref="menuListTree" :data="menuList" :props="{ label: 'permission_name', children: 'children' }" node-key="id" default-expand-all show-checkbox check-strictly @check="handleChange">
                                </el-tree>
                            </el-scrollbar>
                        </div>
					</el-form-item>
				</el-col>
				<!-- <el-col :span="12">
					<el-form-item label="数据权限">
						<el-tree ref="orgListTree" :data="orgList" :props="{ label: 'name', children: 'children' }" node-key="id" accordion show-checkbox>
						</el-tree>
					</el-form-item>
				</el-col> -->
			</el-row>
			<el-row v-if="opType == 4">
				<el-col :span="24">
					<el-form-item label="职务权限">
                        <div class="w100">
                            <el-scrollbar max-height="400px" always :min-size="30">
                                <el-tree ref="postListTree" :data="postList" :props="{ label: 'permission_name', children: 'children' }" node-key="id" default-expand-all>
                                </el-tree>
                            </el-scrollbar>
                        </div>
					</el-form-item>
				</el-col>
				<!-- <el-col :span="12">
					<el-form-item label="数据权限">
						<el-tree ref="orgListTree" :data="orgList" :props="{ label: 'name', children: 'children' }" node-key="id" accordion show-checkbox>
						</el-tree>
					</el-form-item>
				</el-col> -->
			</el-row>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus/es'
import { useUserAddApi, useUserApi, setUserPositionApi, setUserPermissionApi, getUserPositionApi, getUserPermissionApi, updateUserPasswordApi, getPostPermissionApi } from '@/api/user'
import { useRoleList } from '@/api/role'
import { useMenuListApi, useMenuNavApi } from '@/api/menu'
import { elMsg } from '@/utils/message'
import { createRouteList } from '@/router'
import { timeResetDate } from '@/utils/tool'
import { useOrgListApi } from '@/api/org'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const opType = ref(false)
const postList = ref<any[]>([])
const roleList = ref<any[]>([])
const orgList = ref([])
const dataFormRef = ref()
const menuListTree = ref(null)
const orgListTree = ref()
const orgListPopover = ref()
const menuList = ref([])
const allRoute = ref([]);

const dataForm = reactive({
	id: '',
	strator_account: '',
	realName: '',
	orgId: '',
	department_id: '',
	parentName: '',
	orgName: '',
	strator_password: '',
	strator_email: '',
	strator_nickname: '',
	strator_mobile: '',
	position_ids: [] as any[],
	menuIdList: [] as any[],
	status: 1
})

const init = (id?: number, type?: any) => {
	visible.value = true
	dataForm.id = ''
	dataForm.department_id = ''
	dataForm.parentName = ''
	dataForm.strator_account = ''
	dataForm.strator_password = ''
	dataForm.strator_email = ''
	dataForm.strator_nickname = ''
	dataForm.strator_mobile = ''
	dataForm.position_ids = []
	dataForm.menuIdList = []
    postList.value = [];
    opType.value = type;
	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}
    if (type == 1 || type == 4) {
        getUserPosition(id);
    }
    if (type == 2) {
        getUserPermission(id);
    }
    if (type == 4) {
        getPostPermission(id);
    }
    if (id) {
        dataForm.id = id;
		getUser(id)
	} else {
        nextTick(() => {
            orgListTree.value.setCurrentKey('')
        })
    }
}

const dataRules = ref({
	strator_account: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	strator_mobile: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	position_ids: [{ required: true, message: '必填项不能为空', trigger: 'change' }],  
	// strator_password: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
})
// 获取菜单列表
const getMenuList = async () => {
    const { data } = await useMenuNavApi();
    allRoute.value = createRouteList(data);
	useMenuListApi().then(res => {
		menuList.value = createTreeData(res.data);
	})
}
const createTreeData = (list: any[]|undefined) => {
    const treelist = [];
    list.forEach(item => {
        if (item.children?.length) {
            item.children.forEach(e => {
                e.disabled = !allRoute.value.includes(e.route);
            });
        }
        const additem = {
            ...item,
            disabled: !allRoute.value.includes(item.route),
            children: [],
        }
        // 有子菜单的情况
		if (item.children && item.children.length > 0) {
			additem.children?.push(...createTreeData(item.children))
		}
        treelist.push(additem);
    })
    return treelist;
}
const getRolleList = () => {
	return useRoleList().then(res => {
		roleList.value = res.data.data
	})
}
const handleChange = (data, nodes) => {
    // 选中子节点，默认选中父节点
    if (data.type == 1 && nodes.checkedKeys.includes(data.id)) {
        const parentNode = menuList.value.find(i => i.id == data.pid);
        if (parentNode) {
            menuListTree.value.setChecked(parentNode.id, true)
        }
    }
    if (data.type == 2 && nodes.checkedKeys.includes(data.id)) {
        const topNode = menuList.value.find(i => i.children.some(e => e.id == data.pid));
        if (topNode) {
            menuListTree.value.setChecked(topNode.id, true)
            const paraneNode = topNode.children.find(i => i.id == data.pid);
            menuListTree.value.setChecked(paraneNode.id, true)
        }
    }
    // 选中父节点，默认选择所有子节点
    if (data.children?.length) {
        if (nodes.checkedKeys.includes(data.id)) {
            data.children.forEach(item => {
                menuListTree.value.setChecked(item.id, true)
                handleChange(item, {checkedKeys: [item.id]});
            })
        } else {
            data.children.forEach(item => {
                menuListTree.value.setChecked(item.id, false)
                handleChange(item, {checkedKeys: []});
            })
        }
    }
}
const treeCurrentChange = (data: any) => {
	dataForm.department_id = data.id
	dataForm.parentName = data.department_name
	orgListPopover.value.hide()
}
// 上级部门树, 设置默认值
const treeSetDefaultHandle = () => {
	dataForm.department_id = ''
	dataForm.parentName = ''
}
// 获取部门列表
const getOrgList = () => {
	useOrgListApi().then((res: any) => {
		orgList.value = res.data;
	})
}
onMounted(() => {
    getRolleList();
    getMenuList();
    getOrgList();
})
// 获取职务ID
const getUserPosition = (id) => {
    getUserPositionApi(id).then((result) => {
        dataForm.position_ids = result.data || [];
    }).catch((err) => {
        
    });
}
// 获取权限ID
const getUserPermission = (id) => {
    getUserPermissionApi(id).then((result) => {
        if (result.data?.length) {
            result.data.forEach(item => menuListTree.value.setChecked(item, true))
        }
    }).catch((err) => {
        
    });
}
// 获取职务对应的权限
const getPostPermission = (id) => {
    getPostPermissionApi(id).then((result) => {
        postList.value = result.data;
    }).catch((err) => {
        
    });
}
// 获取信息
const getUser = (id: number) => {
	useUserApi(id).then((res: any) => {
        delete res.data.created_at;
        delete res.data.updated_at;
        delete res.data.deleted_at;
		Object.assign(dataForm, res.data)

		// dataForm.menuIdList.forEach(item => menuListTree.value.setChecked(item, true))
		// orgListTree.value.setCheckedKeys(dataForm.orgIdList)
        nextTick(() => {
            orgListTree.value.setCurrentKey(dataForm.department_id)
        })
	})
}
// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
        const params:any = {
            strator_account: dataForm.strator_account,
            strator_mobile: dataForm.strator_mobile,
            department_id: dataForm.department_id,
        };
        if (dataForm.strator_email) {
            params.strator_email = dataForm.strator_email;
        }
        if (dataForm.strator_nickname) {
            params.strator_nickname = dataForm.strator_nickname;
        }
        if (dataForm.strator_password) {
            params.strator_password = dataForm.strator_password;
        }
        if (dataForm.id) {
            params.id = dataForm.id;
            params.updated_at = timeResetDate();
            delete params.strator_password
        }
        // console.log(dataForm.position_ids);
        // return; 
        if (opType.value == 1) {
            // 设置职务
            setUserPositionApi({
                strator_id: dataForm.id,
                position_ids: dataForm.position_ids
            }).then((result) => {
                if (result) {
                    ElMessage.success({
                        message: '操作成功',
                        duration: 500,
                        onClose: () => {
                            visible.value = false
                            emit('refreshDataList')
                        }
                    })
                }
            }).catch((err) => {
                
            });
        } else if (opType.value == 2) {
            // 授予权限
            dataForm.menuIdList = [...menuListTree.value.getHalfCheckedKeys(), ...menuListTree.value.getCheckedKeys()]
            console.log(JSON.parse(JSON.stringify(dataForm.menuIdList)));
            setUserPermissionApi({
                strator_id: dataForm.id,
                permission_ids: dataForm.menuIdList
            }).then((result) => {
                if (result) {
                    ElMessage.success({
                        message: '操作成功',
                        duration: 500,
                        onClose: () => {
                            visible.value = false
                            emit('refreshDataList')
                        }
                    })
                }
            }).catch((err) => {
                
            });
        } else if (opType.value == 3) {
            // 重置密码
            if (!dataForm.strator_password) {
                elMsg('请输入密码', 'warning')
            } else {
                updateUserPasswordApi({
                    id: dataForm.id,
                    strator_password: dataForm.strator_password
                }).then((result) => {
                    if (result) {
                        ElMessage.success({
                            message: '操作成功',
                            duration: 500,
                            onClose: () => {
                                visible.value = false
                                emit('refreshDataList')
                            }
                        })
                    }
                }).catch((err) => {
                    
                });
            }
        } else {
            useUserAddApi(params).then((result) => {
                if (result) {
                    ElMessage.success({
                        message: '操作成功',
                        duration: 500,
                        onClose: () => {
                            visible.value = false
                            emit('refreshDataList')
                        }
                    })
                }
            }).catch((err) => {
                
            });
        }
	})
}

defineExpose({
	init
})
</script>
